<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>js工具函数 | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Array相关sort 计算最大元素123456&#x2F;* * 功能:获取数组中的最大数字 * 描述:sort 返回值(b - a)大于0 则交换元素 *&#x2F;const maxItemOfArray &#x3D; (arr) &#x3D;&gt; arr.sort((a, b) &#x3D;&gt; b - a)[0];let maxItem &#x3D; maxItemOfArray([3, 5, 12, 5]); &#x2F;&#x2F;12  reduce">
<meta property="og:type" content="article">
<meta property="og:title" content="js工具函数">
<meta property="og:url" content="http://example.com/2023/07/22/web/JavaScript/utils/util-js/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="Array相关sort 计算最大元素123456&#x2F;* * 功能:获取数组中的最大数字 * 描述:sort 返回值(b - a)大于0 则交换元素 *&#x2F;const maxItemOfArray &#x3D; (arr) &#x3D;&gt; arr.sort((a, b) &#x3D;&gt; b - a)[0];let maxItem &#x3D; maxItemOfArray([3, 5, 12, 5]); &#x2F;&#x2F;12  reduce">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.689Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.689Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/web/JavaScript/utils/util-js/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'js工具函数',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">js工具函数</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.689Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.689Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="js工具函数"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="Array相关"><a href="#Array相关" class="headerlink" title="Array相关"></a>Array相关</h3><h4 id="sort-计算最大元素"><a href="#sort-计算最大元素" class="headerlink" title="sort 计算最大元素"></a>sort 计算最大元素</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:获取数组中的最大数字</span></span><br><span class="line"><span class="comment"> * 描述:sort 返回值(b - a)大于0 则交换元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">maxItemOfArray</span> = (<span class="params">arr</span>) =&gt; arr.<span class="title function_">sort</span>(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b - a)[<span class="number">0</span>];</span><br><span class="line"><span class="keyword">let</span> maxItem = <span class="title function_">maxItemOfArray</span>([<span class="number">3</span>, <span class="number">5</span>, <span class="number">12</span>, <span class="number">5</span>]); <span class="comment">//12</span></span><br></pre></td></tr></table></figure>

<h4 id="reduce-计算平均值"><a href="#reduce-计算平均值" class="headerlink" title="reduce 计算平均值"></a>reduce 计算平均值</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:求给定数字的平均值</span></span><br><span class="line"><span class="comment"> * 描述:...args 收集所有参数类数组, 收集剩余参数 show(a,b,...args)</span></span><br><span class="line"><span class="comment"> *      args.reduce((a初始值, 或者计算结束后的返回值, b当前元素) =&gt; a + b, 传递给函数的初始值)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">averageOf</span> = (<span class="params">...args</span>) =&gt; args.<span class="title function_">reduce</span>(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a + b, <span class="number">0</span>) / args.<span class="property">length</span>;</span><br><span class="line"><span class="keyword">let</span> average = <span class="title function_">averageOf</span>(<span class="number">5</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">7</span>); <span class="comment">// 4.5</span></span><br></pre></td></tr></table></figure>

<h4 id="every-判断所有元素相等"><a href="#every-判断所有元素相等" class="headerlink" title="every 判断所有元素相等"></a>every 判断所有元素相等</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:检查数组的所有项是否相等</span></span><br><span class="line"><span class="comment"> * 描述:方法用于检测数组所有元素是否都符合指定条件 ,一个不满足，则返回 false</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">areAllEqual</span> = array =&gt; array.<span class="title function_">every</span>(<span class="function"><span class="params">item</span> =&gt;</span> item === array[<span class="number">0</span>]);</span><br><span class="line"><span class="keyword">let</span> check1 = <span class="title function_">areAllEqual</span>([<span class="number">5</span> ,<span class="number">3</span>, <span class="number">5</span>]); <span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h4 id="filter-清除空元素"><a href="#filter-清除空元素" class="headerlink" title="filter 清除空元素"></a>filter 清除空元素</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:从数组中删除false值，包括false，undefined，NaN，empty</span></span><br><span class="line"><span class="comment"> * 描述:arr.filter 返回检测通过(返回值为true)的元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">rmFalseVal</span> = arr =&gt; arr.<span class="title function_">filter</span>(<span class="function"><span class="params">item</span> =&gt;</span> item);</span><br><span class="line"><span class="keyword">let</span> arr = <span class="title function_">rmFalseVal</span>([<span class="number">3</span>, <span class="number">4</span>, <span class="literal">false</span>, <span class="string">&quot;&quot;</span>, <span class="number">5</span>, <span class="literal">true</span>, <span class="literal">undefined</span>, <span class="title class_">NaN</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;0&quot;</span>, <span class="number">0</span>]); <span class="comment">// [3, 4, 5, true, &quot;0&quot;]</span></span><br></pre></td></tr></table></figure>

<h4 id="new-Set-数组去重"><a href="#new-Set-数组去重" class="headerlink" title="new Set() 数组去重"></a><strong>new Set()</strong> 数组去重</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:从数组中删除重复的项</span></span><br><span class="line"><span class="comment"> * 描述:Set 结构成员不会添加重复的值</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">removeDuplicatedValues</span> = array =&gt; [...<span class="keyword">new</span> <span class="title class_">Set</span>(array)];</span><br><span class="line"><span class="keyword">let</span> arr = <span class="title function_">removeDuplicatedValues</span>([<span class="number">5</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">6</span>]); <span class="comment">// [5, 3, 2, 6, 1]</span></span><br></pre></td></tr></table></figure>

<h4 id="删除数组指定元素"><a href="#删除数组指定元素" class="headerlink" title="删除数组指定元素"></a>删除数组指定元素</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:删除数组中指定元素</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">removeAaaryObj</span> = (<span class="params">arr, el</span>) =&gt;&#123;</span><br><span class="line">    <span class="keyword">let</span> array = [];</span><br><span class="line">    arr.<span class="title function_">map</span>(<span class="function">(<span class="params">item,i</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(item != el)&#123;</span><br><span class="line">            array.<span class="title function_">push</span>(item);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> array;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> arrayre = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">4</span>,<span class="string">&#x27;ab&#x27;</span>,<span class="string">&#x27;ab&#x27;</span>,<span class="string">&#x27;cad&#x27;</span>];</span><br><span class="line"><span class="title function_">removeAaaryObj</span>(arrayre,<span class="string">&#x27;ab&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h4 id="数组乱序"><a href="#数组乱序" class="headerlink" title="数组乱序"></a>数组乱序</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">shuffleArray</span> = (<span class="params">arr</span>) =&gt; arr.<span class="title function_">sort</span>(<span class="function">() =&gt;</span> <span class="number">0.5</span> - <span class="title class_">Math</span>.<span class="title function_">random</span>());</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">shuffleArray</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]));</span><br></pre></td></tr></table></figure>



<h3 id="String"><a href="#String" class="headerlink" title="String"></a>String</h3><h4 id="指定字符替换"><a href="#指定字符替换" class="headerlink" title="指定字符替换"></a>指定字符替换</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">findAndReplace</span> = (<span class="params">string, old, newchar</span>) =&gt; string.<span class="title function_">split</span>(old).<span class="title function_">join</span>(newchar);</span><br><span class="line"><span class="keyword">let</span> result = <span class="title function_">findAndReplace</span>(<span class="string">&#x27;I like banana&#x27;</span>, <span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;g&#x27;</span>); <span class="comment">// I like apple</span></span><br></pre></td></tr></table></figure>

<h4 id="指定字符串两边添加"><a href="#指定字符串两边添加" class="headerlink" title="指定字符串两边添加"></a>指定字符串两边添加</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">findAndAdd</span> = (<span class="params">s, o, l, r</span>) =&gt; s.<span class="title function_">replace</span>(<span class="keyword">new</span> <span class="title class_">RegExp</span>(o,<span class="string">&#x27;g&#x27;</span>),<span class="function">(<span class="params">item</span>)=&gt;</span> <span class="string">`<span class="subst">$&#123;l&#125;</span><span class="subst">$&#123;item&#125;</span><span class="subst">$&#123;r&#125;</span>`</span>)</span><br><span class="line"><span class="keyword">let</span> result = <span class="title function_">findAndAdd</span>(<span class="string">&#x27;I like banana&#x27;</span>, <span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;&lt;&#x27;</span>,<span class="string">&#x27;&gt;&#x27;</span>); <span class="comment">// &quot;I like b&lt;a&gt;n&lt;a&gt;n&lt;a&gt;&quot;</span></span><br></pre></td></tr></table></figure>

<h4 id="反转字符串"><a href="#反转字符串" class="headerlink" title="反转字符串"></a>反转字符串</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通过数组 reverse</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">reverseString</span> = str =&gt; [...str].<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line"><span class="keyword">let</span> a = <span class="title function_">reverseString</span>(<span class="string">&#x27;Have a nice day!&#x27;</span>); <span class="comment">// !yad ecin a eva</span></span><br></pre></td></tr></table></figure>

<h4 id="首字母大小"><a href="#首字母大小" class="headerlink" title="首字母大小"></a>首字母大小</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:将字符串中所有单词的第一个字母大写</span></span><br><span class="line"><span class="comment"> * 描述: \b 匹配单词开头或结尾 ，/\b[a-z0-9]/g 匹配单词-&gt; 取一位 -&gt;所有单词</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">capitalizeAllWords</span> = str =&gt; str.<span class="title function_">replace</span>(<span class="regexp">/\b[a-z]/g</span>, <span class="function"><span class="params">char</span> =&gt;</span> char.<span class="title function_">toUpperCase</span>());</span><br><span class="line"><span class="keyword">let</span> claw = <span class="title function_">capitalizeAllWords</span>(<span class="string">&quot;i love reading book&quot;</span>); <span class="comment">// I Love Reading Book</span></span><br></pre></td></tr></table></figure>

<h4 id="指定规则分割字符串"><a href="#指定规则分割字符串" class="headerlink" title="指定规则分割字符串"></a>指定规则分割字符串</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:字符串转换为单词数组</span></span><br><span class="line"><span class="comment"> * 描述:split(regexp) 只要匹配的字符都当做切割符号</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">toWords</span> = (<span class="params">string, pattern = /[^a-zA-Z-]+/</span>) =&gt; string.<span class="title function_">split</span>(pattern);</span><br><span class="line"><span class="keyword">let</span> words = <span class="title function_">toWords</span>(<span class="string">&#x27;I 5 5 wa5nt to be55 come a great false nan programm5er&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="清除字符串两边空格"><a href="#清除字符串两边空格" class="headerlink" title="清除字符串两边空格"></a>清除字符串两边空格</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">trim</span> = (<span class="params">str</span>) =&gt; str.<span class="title function_">replace</span>(<span class="regexp">/(^\s*)|(\s*$)/g</span>, <span class="string">&quot;&quot;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="判断字符串JSON"><a href="#判断字符串JSON" class="headerlink" title="判断字符串JSON"></a>判断字符串JSON</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:字符串是否是有效的JSON</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">isValidJSON</span> = str =&gt; &#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">typeof</span> str == <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// JSON.parse(str) 会通过 123 &quot;123&quot; 数组</span></span><br><span class="line">            <span class="keyword">var</span> obj = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(str);</span><br><span class="line">            <span class="comment">// 数组 &#x27;[object Array]&#x27;</span></span><br><span class="line">            <span class="keyword">if</span>(<span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span>.<span class="title function_">call</span>(obj) == <span class="string">&#x27;[object Object]&#x27;</span>)&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">let</span> ivjson1 = <span class="title function_">isValidJSON</span>(<span class="string">&#x27;1&#x27;</span>); <span class="comment">// false</span></span><br><span class="line"><span class="keyword">let</span> ivjson2 = <span class="title function_">isValidJSON</span>(<span class="string">&#x27;&#123;&quot;title&quot;: &quot;javascript&quot;, &quot;price&quot;: 14&#125;&#x27;</span>); <span class="comment">// true</span></span><br><span class="line"><span class="keyword">let</span> ivjson3 = <span class="title function_">isValidJSON</span>(<span class="string">&#x27;&#123;&quot;title&quot;: &quot;javascript&quot;, &quot;price&quot;: 14, subtitle&#125;&#x27;</span>); <span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h4 id="字符串高亮"><a href="#字符串高亮" class="headerlink" title="字符串高亮"></a>字符串高亮</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> name = <span class="string">&quot;font&quot;</span>；</span><br><span class="line"><span class="keyword">let</span> item = &#123;<span class="attr">name</span>:<span class="string">&#x27;itemfonttmp&#x27;</span>&#125;</span><br><span class="line"><span class="keyword">let</span> reg = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">`[<span class="subst">$&#123;name&#125;</span>]&#123;1&#125;`</span>,<span class="string">&#x27;g&#x27;</span>);</span><br><span class="line">item.<span class="property">highlight</span> = item.<span class="property">name</span>.<span class="title function_">replace</span>(reg,<span class="function">(<span class="params">item</span>)=&gt;</span><span class="string">`&lt;span style=&quot;color:#f00&quot;&gt;<span class="subst">$&#123;item&#125;</span>&lt;/span&gt;`</span>);</span><br></pre></td></tr></table></figure>

<h4 id="解析-query"><a href="#解析-query" class="headerlink" title="解析 query"></a>解析 query</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">getParameters</span> = <span class="variable constant_">URL</span> =&gt; <span class="title class_">JSON</span>.<span class="title function_">parse</span>(<span class="string">`&#123;&quot;<span class="subst">$&#123;<span class="built_in">decodeURI</span>(URL.split(<span class="string">&quot;?&quot;</span>)[<span class="number">1</span>]).replace(/<span class="string">&quot;/g, &#x27;\\&quot;</span><span class="string">&#x27;).replace(/&amp;/g, &#x27;</span><span class="string">&quot;,&quot;</span><span class="string">&#x27;).replace(/=/g, &#x27;</span><span class="string">&quot;:&quot;</span><span class="string">&#x27;)&#125;&quot;&#125;`)</span></span></span></span><br></pre></td></tr></table></figure>

<h4 id="单词首字母大写"><a href="#单词首字母大写" class="headerlink" title="单词首字母大写"></a>单词首字母大写</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">tuc</span> = str =&gt; str.<span class="title function_">replace</span>(<span class="regexp">/(?=\b)\w/g</span>,<span class="function">(<span class="params">x</span>)=&gt;</span> x.<span class="title function_">toUpperCase</span>())</span><br><span class="line"><span class="title function_">tuc</span>(<span class="string">&quot;follow for more&quot;</span>)</span><br></pre></td></tr></table></figure>



<h3 id="Math相关"><a href="#Math相关" class="headerlink" title="Math相关"></a>Math相关</h3><h4 id="指定范围随机数"><a href="#指定范围随机数" class="headerlink" title="指定范围随机数"></a>指定范围随机数</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 通过最小范围 + 最大减最小所得到的随机数</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">randomNum</span> = (<span class="params">min, max</span>) =&gt; &#123;</span><br><span class="line">   <span class="keyword">return</span> <span class="title class_">Math</span>.<span class="title function_">floor</span>(min + <span class="title class_">Math</span>.<span class="title function_">random</span>() * (max - min));</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">randomNum</span>(<span class="number">5</span>,<span class="number">10</span>))</span><br></pre></td></tr></table></figure>

<h4 id="随机颜色"><a href="#随机颜色" class="headerlink" title="随机颜色"></a>随机颜色</h4><ul>
<li><p><strong>0x1000000</strong>: <code>#ffffff + 1</code> (16777216)</p>
</li>
<li><p><strong>&lt;&lt; 0</strong>：去除小数(按位运算内部会调用<strong>Call <a target="_blank" rel="noopener" href="http://bclary.com/2004/11/07/#a-9.5">ToInt32()</a></strong>,里面有调用一个 <code>floor(x)&#123;return x-(x % 1)&#125;</code>)</p>
</li>
<li><p><strong>.slice(-6)</strong>: 补0,从后面截取6位数</p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">randomColor</span> = (<span class="params"></span>) =&gt; <span class="string">&#x27;#&#x27;</span> + (<span class="string">&#x27;00000&#x27;</span> + (<span class="title class_">Math</span>.<span class="title function_">random</span>() * <span class="number">0x1000000</span> &lt;&lt; <span class="number">0</span>).<span class="title function_">toString</span>(<span class="number">16</span>)).<span class="title function_">slice</span>(-<span class="number">6</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">randomColor</span>())</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">randomHexColor</span> = (<span class="params"></span>) =&gt; <span class="string">`#<span class="subst">$&#123;<span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">0xffffff</span>).toString(<span class="number">16</span>).padEnd(<span class="number">6</span>, <span class="string">&quot;0&quot;</span>)&#125;</span>`</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">randomHexColor</span>())</span><br></pre></td></tr></table></figure>

<h4 id="RGB转十六进制"><a href="#RGB转十六进制" class="headerlink" title="RGB转十六进制"></a>RGB转十六进制</h4><ul>
<li><strong>padStart(6, “0”)</strong>:不足六位的值 用0在前面填充到六位</li>
<li><strong>位置调整</strong>:<code>(r &lt;&lt; 16) + (g &lt;&lt; 8) + b</code>( r 移到 56 位置，g 移动 34 位置，b 12位置不变 )</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">RGBToHex</span> = (<span class="params">r, g, b</span>) =&gt; ((r &lt;&lt; <span class="number">16</span>) + (g &lt;&lt; <span class="number">8</span>) + b).<span class="title function_">toString</span>(<span class="number">16</span>).<span class="title function_">padStart</span>(<span class="number">6</span>, <span class="string">&quot;0&quot;</span>);</span><br><span class="line"><span class="keyword">let</span> hex = <span class="title class_">RGBToHex</span>(<span class="number">0</span>, <span class="number">255</span>, <span class="number">255</span>); <span class="comment">// ffffff</span></span><br></pre></td></tr></table></figure>

<h3 id="Object"><a href="#Object" class="headerlink" title="Object"></a>Object</h3><h4 id="检测对象是否为空"><a href="#检测对象是否为空" class="headerlink" title="检测对象是否为空 {}"></a>检测对象是否为空 {}</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Reflect.ownKeys(obj) 获取对象自身的属性键组成的数组</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">isEmpty</span> = obj =&gt; <span class="title class_">Reflect</span>.<span class="title function_">ownKeys</span>(obj).<span class="property">length</span> === <span class="number">0</span> &amp;&amp; obj.<span class="property">constructor</span> === <span class="title class_">Object</span>;</span><br></pre></td></tr></table></figure>



<h3 id="Date-相关"><a href="#Date-相关" class="headerlink" title="Date 相关"></a>Date 相关</h3><h4 id="直接获取时间"><a href="#直接获取时间" class="headerlink" title="直接获取时间"></a>直接获取时间</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:返回时间</span></span><br><span class="line"><span class="comment"> * 描述:date.toTimeString   11:19:44 GMT+0800 (中国标准时间)</span></span><br><span class="line"><span class="comment">    	console.log(new Date(1597894083000).toLocaleString())      // 2020/8/20 上午11:26:29</span></span><br><span class="line"><span class="comment">   	    console.log(new Date().toLocaleTimeString())</span></span><br><span class="line"><span class="comment">    	console.log(new Date(1597894083000).toLocaleDateString())  // 2020/8/20</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">getTimeFromDate</span> = date =&gt; date.<span class="title function_">toTimeString</span>().<span class="title function_">slice</span>(<span class="number">0</span>, <span class="number">8</span>);</span><br><span class="line"><span class="keyword">let</span> time1 = <span class="title function_">getTimeFromDate</span>(<span class="keyword">new</span> <span class="title class_">Date</span>()); <span class="comment">// 09:46:08</span></span><br></pre></td></tr></table></figure>

<h4 id="通过日期查询-年终天数"><a href="#通过日期查询-年终天数" class="headerlink" title="通过日期查询 年终天数"></a>通过日期查询 年终天数</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">dayOfYear</span> = (<span class="params">date</span>) =&gt;  <span class="title class_">Math</span>.<span class="title function_">floor</span>((date - <span class="keyword">new</span> <span class="title class_">Date</span>(date.<span class="title function_">getFullYear</span>(), <span class="number">0</span>, <span class="number">0</span>)) / <span class="number">1000</span> / <span class="number">60</span> / <span class="number">60</span> / <span class="number">24</span>);</span><br><span class="line"><span class="title function_">dayOfYear</span>(<span class="keyword">new</span> <span class="title class_">Date</span>());</span><br></pre></td></tr></table></figure>



<h3 id="Number-相关"><a href="#Number-相关" class="headerlink" title="Number 相关"></a>Number 相关</h3><h4 id="判断是否数组"><a href="#判断是否数组" class="headerlink" title="判断是否数组"></a>判断是否数组</h4><blockquote>
<p>  isFinite、parseFloat、Number</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 功能:验证数字是否有效</span></span><br><span class="line"><span class="comment"> * 描述: parseFloat(n) 第一个字符不能被转换为数字，那么会返回 NaN,否则返回第一个数值</span></span><br><span class="line"><span class="comment"> 		isFinite(n) number 是 NaN（非数字），或者是正、负无穷大的数，则返回 false。</span></span><br><span class="line"><span class="comment"> 		Number(n) 将对象转数字</span></span><br><span class="line"><span class="comment"> 		Number(Infinity) === Infinity //true</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">isValidNumber</span> = n =&gt; !<span class="built_in">isNaN</span>(<span class="built_in">parseFloat</span>(n)) &amp;&amp; <span class="built_in">isFinite</span>(n) &amp;&amp; <span class="title class_">Number</span>(n) === n;</span><br><span class="line"><span class="keyword">let</span> ivn = <span class="title function_">isValidNumber</span>(<span class="number">10</span>); <span class="comment">// true</span></span><br><span class="line"><span class="keyword">let</span> ivn2 = <span class="title function_">isValidNumber</span>(<span class="string">&quot;a&quot;</span>); <span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h3 id="环境判断相关"><a href="#环境判断相关" class="headerlink" title="环境判断相关"></a>环境判断相关</h3><h4 id="判断是否是手机"><a href="#判断是否是手机" class="headerlink" title="判断是否是手机"></a>判断是否是手机</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">isMobile</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> flag = navigator.<span class="property">userAgent</span>.<span class="title function_">match</span>(<span class="regexp">/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i</span>)</span><br><span class="line">    <span class="keyword">return</span> flag;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="检测设备类型"><a href="#检测设备类型" class="headerlink" title="检测设备类型"></a>检测设备类型</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">judgeDeviceType</span> =</span><br><span class="line">      (<span class="params"></span>) =&gt; <span class="regexp">/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i</span>.<span class="title function_">test</span>(navigator.<span class="property">userAgent</span>) ? <span class="string">&#x27;Mobile&#x27;</span> : <span class="string">&#x27;PC&#x27;</span>;</span><br></pre></td></tr></table></figure>



<h4 id="浏览器选项卡是否激活"><a href="#浏览器选项卡是否激活" class="headerlink" title="浏览器选项卡是否激活"></a>浏览器选项卡是否激活</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">isTabActive</span> = (<span class="params"></span>) =&gt; !<span class="variable language_">document</span>.<span class="property">hidden</span>; </span><br></pre></td></tr></table></figure>

<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><h4 id="获取选择的文本"><a href="#获取选择的文本" class="headerlink" title="获取选择的文本"></a>获取选择的文本</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">getSelectedText</span> = (<span class="params"></span>) =&gt; <span class="variable language_">window</span>.<span class="title function_">getSelection</span>().<span class="title function_">toString</span>();</span><br><span class="line"><span class="title function_">getSelectedText</span>();</span><br></pre></td></tr></table></figure>







</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/web/JavaScript/utils/util-js/">http://example.com/2023/07/22/web/JavaScript/utils/util-js/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/tmp/%E8%A7%86%E9%A2%91%E8%A7%A3%E6%9E%90%E6%8A%80%E6%9C%AF/" title=""><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/web/JavaScript/%E5%9E%83%E5%9C%BE%E6%A1%B6/h5-model-localvideo/" title="h5 本地摄像头视频采集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">h5 本地摄像头视频采集</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Array%E7%9B%B8%E5%85%B3"><span class="toc-number">1.</span> <span class="toc-text">Array相关</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#sort-%E8%AE%A1%E7%AE%97%E6%9C%80%E5%A4%A7%E5%85%83%E7%B4%A0"><span class="toc-number">1.1.</span> <span class="toc-text">sort 计算最大元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#reduce-%E8%AE%A1%E7%AE%97%E5%B9%B3%E5%9D%87%E5%80%BC"><span class="toc-number">1.2.</span> <span class="toc-text">reduce 计算平均值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#every-%E5%88%A4%E6%96%AD%E6%89%80%E6%9C%89%E5%85%83%E7%B4%A0%E7%9B%B8%E7%AD%89"><span class="toc-number">1.3.</span> <span class="toc-text">every 判断所有元素相等</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#filter-%E6%B8%85%E9%99%A4%E7%A9%BA%E5%85%83%E7%B4%A0"><span class="toc-number">1.4.</span> <span class="toc-text">filter 清除空元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#new-Set-%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D"><span class="toc-number">1.5.</span> <span class="toc-text">new Set() 数组去重</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%95%B0%E7%BB%84%E6%8C%87%E5%AE%9A%E5%85%83%E7%B4%A0"><span class="toc-number">1.6.</span> <span class="toc-text">删除数组指定元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B0%E7%BB%84%E4%B9%B1%E5%BA%8F"><span class="toc-number">1.7.</span> <span class="toc-text">数组乱序</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#String"><span class="toc-number">2.</span> <span class="toc-text">String</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8C%87%E5%AE%9A%E5%AD%97%E7%AC%A6%E6%9B%BF%E6%8D%A2"><span class="toc-number">2.1.</span> <span class="toc-text">指定字符替换</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8C%87%E5%AE%9A%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%A4%E8%BE%B9%E6%B7%BB%E5%8A%A0"><span class="toc-number">2.2.</span> <span class="toc-text">指定字符串两边添加</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">2.3.</span> <span class="toc-text">反转字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%A6%96%E5%AD%97%E6%AF%8D%E5%A4%A7%E5%B0%8F"><span class="toc-number">2.4.</span> <span class="toc-text">首字母大小</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8C%87%E5%AE%9A%E8%A7%84%E5%88%99%E5%88%86%E5%89%B2%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">2.5.</span> <span class="toc-text">指定规则分割字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B8%85%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%A4%E8%BE%B9%E7%A9%BA%E6%A0%BC"><span class="toc-number">2.6.</span> <span class="toc-text">清除字符串两边空格</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E5%AD%97%E7%AC%A6%E4%B8%B2JSON"><span class="toc-number">2.7.</span> <span class="toc-text">判断字符串JSON</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%AB%98%E4%BA%AE"><span class="toc-number">2.8.</span> <span class="toc-text">字符串高亮</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E6%9E%90-query"><span class="toc-number">2.9.</span> <span class="toc-text">解析 query</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E8%AF%8D%E9%A6%96%E5%AD%97%E6%AF%8D%E5%A4%A7%E5%86%99"><span class="toc-number">2.10.</span> <span class="toc-text">单词首字母大写</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Math%E7%9B%B8%E5%85%B3"><span class="toc-number">3.</span> <span class="toc-text">Math相关</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8C%87%E5%AE%9A%E8%8C%83%E5%9B%B4%E9%9A%8F%E6%9C%BA%E6%95%B0"><span class="toc-number">3.1.</span> <span class="toc-text">指定范围随机数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9A%8F%E6%9C%BA%E9%A2%9C%E8%89%B2"><span class="toc-number">3.2.</span> <span class="toc-text">随机颜色</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#RGB%E8%BD%AC%E5%8D%81%E5%85%AD%E8%BF%9B%E5%88%B6"><span class="toc-number">3.3.</span> <span class="toc-text">RGB转十六进制</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Object"><span class="toc-number">4.</span> <span class="toc-text">Object</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A3%80%E6%B5%8B%E5%AF%B9%E8%B1%A1%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA"><span class="toc-number">4.1.</span> <span class="toc-text">检测对象是否为空 {}</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Date-%E7%9B%B8%E5%85%B3"><span class="toc-number">5.</span> <span class="toc-text">Date 相关</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B4%E6%8E%A5%E8%8E%B7%E5%8F%96%E6%97%B6%E9%97%B4"><span class="toc-number">5.1.</span> <span class="toc-text">直接获取时间</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E8%BF%87%E6%97%A5%E6%9C%9F%E6%9F%A5%E8%AF%A2-%E5%B9%B4%E7%BB%88%E5%A4%A9%E6%95%B0"><span class="toc-number">5.2.</span> <span class="toc-text">通过日期查询 年终天数</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Number-%E7%9B%B8%E5%85%B3"><span class="toc-number">6.</span> <span class="toc-text">Number 相关</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E6%95%B0%E7%BB%84"><span class="toc-number">6.1.</span> <span class="toc-text">判断是否数组</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%8E%AF%E5%A2%83%E5%88%A4%E6%96%AD%E7%9B%B8%E5%85%B3"><span class="toc-number">7.</span> <span class="toc-text">环境判断相关</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E6%98%AF%E6%89%8B%E6%9C%BA"><span class="toc-number">7.1.</span> <span class="toc-text">判断是否是手机</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A3%80%E6%B5%8B%E8%AE%BE%E5%A4%87%E7%B1%BB%E5%9E%8B"><span class="toc-number">7.2.</span> <span class="toc-text">检测设备类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E9%80%89%E9%A1%B9%E5%8D%A1%E6%98%AF%E5%90%A6%E6%BF%80%E6%B4%BB"><span class="toc-number">7.3.</span> <span class="toc-text">浏览器选项卡是否激活</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96"><span class="toc-number"></span> <span class="toc-text">其他</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E9%80%89%E6%8B%A9%E7%9A%84%E6%96%87%E6%9C%AC"><span class="toc-number">0.1.</span> <span class="toc-text">获取选择的文本</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>